import jwt
from django.http import HttpResponse

from config import token_config
from cyxmall import settings
from utils.resFormatUtil import ResFormat


class TokenMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request, *args, **kwargs):
        # 获取请求之前执行的代码
        # 获取token
        authorization_token = request.META.get('HTTP_AUTHORIZATION')
        # 获取当前API信息
        api = f'{request.method}:{request.path}'
        if api in settings.TOKEN_API:
            # 1.判断是否有token
            if not authorization_token:
                return ResFormat(status='ACCESS_RESTRICTION').json_response()
            else:
                print(authorization_token)
            # 解析token
            try:
                decode_jwt = jwt.decode(authorization_token, token_config.TOKEN_SECRET_KEY,algorithms=token_config.ALG0RITHM)
                # 给request增加email属性
                setattr(request, 'email', decode_jwt.get('email'))
            # print(decode_jwt)
            # 2.判断token是否过期
            except jwt.exceptions.ExpiredSignatureError:
                return ResFormat(status='LOGIN_OUTTIME').json_response()
            # 3.令牌是否正确
            except jwt.exceptions.DecodeError:
                return ResFormat(status='PARAMS_ERROR').json_response()
            # 4.其它错误
            except Exception:
                return ResFormat(status='UNKNOWN_ERROR').json_response()

        # 发送请求获取响应的代码
        response = self.get_response(request)
        # 响应请求
        return response
